/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
// import LayoutEmpty from '@/view/empty/empty.vue'
// import Layout from '@/view/layout/index.vue'
import dayjs from 'dayjs'
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 格式化后台传过来的json数据为路由格式
 * @param routes asyncRoutes
 * @param token
 */
function calComponent(item) {
  // const routeAllPathToCompMap = import.meta.glob(`../views/**/*.vue`);
  // console.log(item.jump);
  const modules = import.meta.glob('@/view/**/*.vue')
  // 养老地图
  // if (item.jump === '/YLDT' || item.jump === '/SPJK') {
  //   return LayoutEmpty
  // }
  // if (item.jump === '/YLDT/RZLR') {
  //   return () => Promise.resolve(require(`@/views/YLDT/RZLR`))
  // }
  // if (item.type === 1 && item.pid === 'root') { // 一级目录
  //   return ()=>import('@/view/layout/index.vue')
  // }
  // if (item.type === 1 && item.pid !== 'root') {
  //   return ()=>import('@/view/empty/empty.vue')
  // }
  if (item.jump.indexOf('workbench') != -1) {
    return modules['/src/view' + item.jump + '.vue']
  } else {
    return modules['/src/view' + item.jump + '/index.vue']
  }
}
function calRedirect(item) {
  if (item.children && item.children[0] && item.children[0].jump) {
    return item.children[0].jump
  } else {
    return ''
  }
}

export function changeSize(limit) {
  var size = "";
  if (limit < 0.1 * 1024) {                            //小于0.1KB，则转化成B
    size = limit.toFixed(2) + "B"
  } else if (limit < 0.1 * 1024 * 1024) {            //小于0.1MB，则转化成KB
    size = (limit / 1024).toFixed(2) + "KB"
  } else if (limit < 0.1 * 1024 * 1024 * 1024) {        //小于0.1GB，则转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + "MB"
  } else {                                            //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB"
  }

  var sizeStr = size + "";                        //转成字符串
  var index = sizeStr.indexOf(".");                    //获取小数点处的索引
  var dou = sizeStr.substr(index + 1, 2)            //获取小数点后两位的值
  if (dou == "00") {                                //判断后两位是否为00，如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size
}


export function formatRoutesByGG(menu, val) {
  let level = 1
  const asyncRoutes = []
  menu.forEach(item => {
    if (item.type === 1 || item.type === 2) {
      if (val) {
        level = val + 1
      }
      const routerObj = {
        path: item.jump,
        component: calComponent(item),
        name: item.code,
        redirect: calRedirect(item),
        hidden: item.isDisplayInMainMenu == 0,
        meta: {
          title: item.name,
          icon: item.icon,
          id: item.id,
          hidden: item.isDisplayInMainMenu === 0,
          keepAlive: false,
          closeTab: true
        },
        level,
        children: item.children ? formatRoutesByGG(item.children, level) : []
      }
      asyncRoutes.push(routerObj)
    }
  })
  return asyncRoutes
}

// sessionStorage 封装 存取加解密
export const sStorage = {
  set: (key, value) => {
    // STORAGE.set(encrypto(key), encrypto(JSON.stringify(value)))
    return STORAGE.set(key, value)
  },
  get: key => {
    // 1.先把需要获取的name值加密
    // 2.sessionStorage获取name值对应的value(加密后的value)
    // 3.解密value值
    // const val = STORAGE.get(encrypto(key))
    // if (val) {
    //   console.log(decrypto(val))
    // }
    // return val ? JSON.parse(decrypto(val)) : ''
    return STORAGE.get(key)
  },
  delete: (key, value) => {
    // STORAGE.delete(decrypto(encrypto(key)))
    return STORAGE.delete(key)
  },
  clearAll: (key, value) => {
    // STORAGE.clear()
    return STORAGE.clear()
  }
}

// 根据身份证号算出 年龄 出生日期 性别
// type:Number类型 1出生日期 2.性别 3.年龄
export function calAgeAndSexByIdCard(idCard, type, text) {
  const regIdCard =
    /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if(!idCard || !regIdCard.test(idCard)){
    return null;
  }
  if (type === 1) {
    // 获取出生日期
    const birth =
      idCard.substring(6, 10) +
      '-' +
      idCard.substring(10, 12) +
      '-' +
      idCard.substring(12, 14)
    return birth
  }
  if (type === 2) {
    // 获取性别
    if (parseInt(idCard.substr(16, 1)) % 2 === 1) {
      // 男
      return text ? '男' : '1'
    } else {
      // 女
      return text ? '女' : '2'
    }
  }
  if (type === 3) {
    const birthYearMonthDay =
      idCard.substring(6, 10) +
      '-' +
      idCard.substring(10, 12) +
      '-' +
      idCard.substring(12, 14)
    const birthDate = new Date(birthYearMonthDay);
    // 获取年龄
    const momentDate = new Date();
    momentDate.setHours(0, 0, 0, 0); //因为new Date()出来的时间是当前的时分秒。我们需要把时分秒重置为0。使后面时间比较更精确
    const thisYearBirthDate = new Date(
      momentDate.getFullYear(),
      birthDate.getMonth(),
      birthDate.getDate()
    );
    const aDate = thisYearBirthDate - birthDate;
    const bDate = momentDate - birthDate;
    let tempAge = momentDate.getFullYear() - birthDate.getFullYear();
    let age = null;
    if (bDate < aDate) {
      tempAge = tempAge - 1;
      age = tempAge < 0 ? 0 : tempAge;
    } else {
      age = tempAge;
    }
    return age;
  }
}

// 根据出生日期计算年龄 传入YYYY-MM-DD
export function getAgeByBirthday(birthDay) {
  if (birthDay) {
    var birthDayNum = birthDay.split('-').join('')
    var myDate = new Date()
    var month = myDate.getMonth() + 1
    var day = myDate.getDate()
    var age = myDate.getFullYear() - birthDayNum.substring(0, 4) - 1
    if (
      birthDayNum.substring(4, 6) < month ||
      (birthDayNum.substring(4, 6) === month && birthDayNum.substring(6, 8) <= day)
    ) {
      age++
    }
    return age
  }
}

// 处理area-cascader返回的数组
// type:处理字段属性名
// arr： area-cascader返回的数组
const AREA_KEY_NAME = {
  1: ['provinceCode', 'cityCode', 'countyCode', 'streetCode', 'communityCode'],
  2: [
    'unitProvinceCode',
    'unitCityCode',
    'unitCountyCode',
    'unitStreetCode',
    'unitCommunityCode'
  ],
  3: [
    'currentProvinceCode',
    'currentCityCode',
    'currentCountyCode',
    'currentStreetCode',
    'currentCommunityCode'
  ],
  4: [
    'registerProvinceCode',
    'registerCityCode',
    'registerCountyCode',
    'registerStreetCode',
    'registerCommunityCode'
  ],
  5: [
    'reservationCurrentProvinceCode',
    'reservationCurrentCityCode',
    'reservationCurrentCountyCode',
    'reservationCurrentStreetCode',
    'reservationCurrentCommunityCode'
  ],
  6: [
    'permanentProvinceCode',
    'permanentCityCode',
    'permanentCountyCode',
    'permanentStreetCode',
    'permanentCommunityCode'
  ]
}
export function renderAreaCode(type, arr, targetObj) {
  // let result = {}
  AREA_KEY_NAME[type].map((item, index) => {
    targetObj[item] = arr[index] ? arr[index] : ''
    // result[item] = arr[index]?arr[index]:''
  })
  // return result
}

// 把接口返回的区划数据 处理为数组
export function renderAreaArr(type, obj) {
  let areaArr = []
  AREA_KEY_NAME[type].map((item, index) => {
    obj[item] && areaArr.push(obj[item])
  })
  return areaArr
}

export function disabledNextDate(date) {
  return dayjs().isBefore(dayjs(date))
}

export function Percentage(num, total) {
  if (num == 0 || total == 0) {
    return 0;
  }
  return (Math.round(num / total * 10000) / 100.00);// 小数点后两位百分比
}

// 将秒数转化为天时分秒
export function setSeconds(value) {
  if(value == null){
    return "0秒";
  }
  var result = ""
  var sencond = parseInt(value)
  //3600秒等于60分钟等于1小时
  if (sencond > 3600 * 24) {  //表示大于一天
    var day = sencond / (3600 * 24);
    sencond = sencond % (3600 * 24);    //求天数整除外剩余的秒数
    var hour = sencond / 3600;          //1小时==60分钟==3600秒，所以剩余的秒数÷3600= 得到几个小时数
    result = parseInt(day) + "天" + parseInt(hour) + "时";
  } else if (sencond > 3600) {     //表示大于一个小时
    var hour = sencond / 3600;
    var minute = sencond % 3600 / 60;         //求小时数整除外剩余的秒数， 秒数÷60秒 = 得到几分钟
    result = parseInt(hour) + "时" + parseInt(minute) + "分";
  } else if (sencond > 60) {  //表示大于一分钟
    var minute = sencond / 60;
    var sec = sencond % 60;           //求分钟数整除外剩余的秒数
    result = parseInt(minute) + "分" + parseInt(sec) + "秒";
  } else {  //不大于一天、不大于一个小时、也不大于一分钟，那就是秒数
    result = "" + parseInt(sencond) + "秒";
  }
  return result
}
